package com.osdp.sc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.osdp.sc.entity.ScPermission;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

@Mapper
public interface ScPermissionMapper extends BaseMapper<ScPermission> {


    /**
     * 根据用户查询用户下的所有资源
     * @param userId String 用户ID
     * @param permsType String  资源类型，为空时，查询所有资源
     * @return List<ScPermission>
     */
    @Select({"<script>" +
            "select p.* from sc_permission p where exists ( " +
            "select rp.id from sc_role_permission rp " +
            "left join sc_role r on rp.role_id = r.id " +
            "left join sc_role_user ur on r.id = ur.role_id " +
            "where p.id = rp.permission_id and r.validation = '1'" +
            "<if test=\"userId !=null and userId !=''\">" +
            " and ur.user_id = #{userId} " +
            "</if> )" +
            "<if test=\"permsType !=null and permsType !=''\">" +
            " and p.perms_type = #{permsType} " +
            "</if>" +
            "and p.validation = '1' order by p.sort_no asc" +
            "</script>"})
    List<ScPermission> queryPermissionByUserId(@Param("userId") String userId, @Param("permsType") String permsType);

    /**
     * 根据角色编码查询权限
     * @param roleCodes Set<String>
     * @param tenantId String
     * @return
     */
    @Select({"<script>" +
            "select p.* from sc_permission p where exists ( " +
            "select rp.id from sc_role_permission rp " +
            "left join sc_role r on rp.role_id = r.id " +
            "where p.id = rp.permission_id and r.validation = '1'" +
            "<if test=\"roleCodes !=null\">" +
            " and r.role_code in " +
            "<foreach collection=\"roleCodes\" open=\"(\" close=\")\" separator=\",\" item=\"item\">#{item}</foreach>"+
            "</if> )" +
            "<if test=\"tenantId !=null and tenantId !=''\">" +
            " and p.tenant_id = #{tenantId} " +
            "</if>" +
            "and p.validation = '1' order by p.sort_no asc" +
            "</script>"})
    List<ScPermission> queryPermissionByRoleCodes(@Param("roleCodes") Set<String> roleCodes,
                                                  @Param("tenantId") String tenantId);
}
